import ansible_runner
import json
from typing import Dict, List


class MyServer:
    def __init__(self):
        # 环境变量配置
        self.envvars = {
            'ANSIBLE_HOST_KEY_CHECKING': 'False',
            'ANSIBLE_SSH_ARGS': '-o StrictHostKeyChecking=no'
        }

        # 主机清单（建议从外部文件或数据库加载）
        self.inventory = {
            "all": {
                "hosts": {
                    "host1": {
                        "ansible_host": "192.168.6.13",
                        "ansible_user": "root",
                        "ansible_password": "123456",  # 使用密码认证
                        "ansible_port": 22,
                    },
                    "host2": {
                        "ansible_host": "192.168.6.14",
                        "ansible_user": "ubuntu",
                        "ansible_password": "123456",  # 使用密码认证
                        "ansible_port": 22,
                    },
                }
            }
        }

    def exec_cmd(self, command: str) -> Dict[str, List[str]]:
        try:
            result = ansible_runner.run(
                inventory=self.inventory,
                host_pattern="all",  # 对所有主机执行
                module="shell",  # 使用 shell 模块执行命令
                module_args=command,
                envvars=self.envvars,
                quiet=True  # 禁用默认输出，自行处理
            )
            print("###################")
            print(result.status)
            print(result.stderr)
            print(result.stdout)
            print(result.stats)
            print("###################")
            # 解析结果
            success_hosts = []
            failed_hosts = {}
            for event in result.events:
                if event['event'] == 'runner_on_ok':
                    host = event['event_data']['host']
                    success_hosts.append(host)
                    print(f"[SUCCESS] {host}: {event['event_data']['res']['stdout']}")

                elif event['event'] == 'runner_on_failed':
                    host = event['event_data']['host']
                    error = event['event_data']['res'].get('stderr', 'Unknown error')
                    failed_hosts[host] = error
                    print(f"[FAILED] {host}: {error}")

            return {
                "success": success_hosts,
                "failed": failed_hosts
            }
        except Exception as e:
            print(f"Ansible执行异常: {str(e)}")
            return {
                "success": [],
                "failed": {"global_error": str(e)}
            }
